package com.wg.es.job;

import com.wg.es.service.AQIPredictService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.concurrent.CountDownLatch;

/**
 * Created by xiaoq on 2019-05-13 09:58.
 */
@Component
@Slf4j
public class PreJob implements Job, ApplicationContextAware {

    private static CountDownLatch latch = new CountDownLatch(1);
    private static ApplicationContext applicationContext;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        AQIPredictService aqiPredictService = null;
        log.info("Job is running");
        try {
            aqiPredictService = applicationContext.getBean(AQIPredictService.class);
        }catch (Exception e){
            //skip
        }

        if (null != aqiPredictService)
            aqiPredictService.preAQI();
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        new Thread(() ->{
            if (latch.getCount() >= 1) {
                applicationContext = context;
                latch.countDown();
            }
        }).start();
    }

    public static void await() {

        try {
            latch.await();
        } catch (InterruptedException e) {

        }
    }
}
